package com.sprocomm.wxkey;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.Instrumentation;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.DeadObjectException;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import java.util.List;

/**
 * Created by Administrator on 2017/3/24.
 */

public class WXKeyService extends AccessibilityService {

    private static final String TAG = "dingfeng";

    /**
     * 微信的包名
     */
    static final String WECHAT_PACKAGENAME = "com.tencent.mm";
    /**
     * 红包消息的关键字
     */
    static final String ENVELOPE_TEXT_KEY = "[微信红包]";

    Handler handler = new Handler();

    private boolean hasNotify = false;


    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "onReceive....");
            String action = intent.getAction();
            if ("com.sprocomm.wxkey.UP".equals(action)) {
                // record end, send voice

            } else if ("com.sprocomm.wxkey.LONGPRESS".equals(action)) {
                // long press wxkey, start record

            }
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.sprocomm.wxkey.UP");
        filter.addAction("com.sprocomm.wxkey.LONGPRESS");
        registerReceiver(receiver, filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    @Override
    protected boolean onGesture(int gestureId) {
        Log.d(TAG, "onGesture......");
        return super.onGesture(gestureId);
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        final int eventType = event.getEventType();
        Log.i(TAG, "-------------------------------------------------------------");
        Log.i(TAG, "Source Class:" + event.getClassName() + ""); // 事件源的类名
        Log.i(TAG, "Description:" + event.getContentDescription() + ""); // 事件源描述
        Log.i(TAG, "Event Type(int):" + eventType + "");
        for (CharSequence txt : event.getText()) {
            Log.i(TAG, "text:" + txt);
        }
        switch (eventType) {
            case AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED:
                Log.d(TAG, "TYPE_NOTIFICATION_STATE_CHANGED");
                openAppByNotification(event);
                hasNotify = true;
                break;
            case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
                Log.d(TAG, "TYPE_WINDOW_STATE_CHANGED");
                break;
            case AccessibilityEvent.TYPE_VIEW_CLICKED:
                Log.d(TAG, "TYPE_VIEW_CLICKED");
                break;
            case AccessibilityEvent.TYPE_VIEW_LONG_CLICKED:
                Log.d(TAG, "TYPE_VIEW_LONG_CLICKED");
                break;
            default:
                Log.i(TAG, "DEFAULT");
                if (hasNotify) { // 如果有通知
                    fillInputBar();
                }
                break;
        }

        for (CharSequence txt : event.getText()) {
            Log.i(TAG, "text:" + txt);
        }
        Log.i(TAG, "-------------------------------------------------------------");
    }

    private void fillInputBar() {
        try {
            Thread.sleep(1000); // 停1秒, 否则在微信主界面没进入聊天界面就执行了fillInputBar
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (fillInputBar("发一个")) { // 找到输入框，即EditText
            findAndPerformAction("android.widget.Button", "发送"); // 点击发送
            handler.postDelayed(new Runnable() { // 返回主界面，这里延迟执行，为了有更好的交互
                @Override
                public void run() {
                    performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK);   // 返回
                }
            }, 1500);
        }
        hasNotify = false;
    }

    @Override
    protected boolean onKeyEvent(KeyEvent event) {
        int keyCode = event.getKeyCode();
        if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                Log.d(TAG, "onKeyEvent......down");

                test();

//                findAndPerformAction("android.widget.ImageButton", "切换到按住说话");
//                findAndPerformAction("android.widget.ImageButton", "切换到键盘");
//                findAndPerformAction("android.widget.Button", "按住 说话");

/*               AccessibilityNodeInfo node = findAction("android.widget.ImageButton", "切换到按住说话");
                if (node != null) {
                    node.performAction(AccessibilityNodeInfo.ACTION_CLICK); // 执行点击
                } else {
                    node = findAction("android.widget.ImageButton", "切换到键盘");
                    if (node != null) {
                        node.performAction(AccessibilityNodeInfo.ACTION_CLICK); // 执行点击
                    }
                }*/

            } else if (event.getAction() == KeyEvent.ACTION_UP) {
                Log.d(TAG, "onKeyEvent......up");
                //

            }

        }

//        return true;
        return super.onKeyEvent(event);
    }

    private void test() {
        final Instrumentation mInst = new Instrumentation();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "run send pointer...");
//                mInst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),
//                        SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 509, 1724, 0));

                mInst.sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),
                        SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 143, 464, 0));
            }
        }).start();
    }

    public void findWidget(AccessibilityNodeInfo info) {
        if (info.getChildCount() == 0) {
            if (info.getText() != null) {
                Log.i(TAG, "控件名称:" + info.getClassName());
                Log.i(TAG, "控件中的值：" + info.getText());

                if ("切换到按住说话".equals(info.getText().toString())) {
                    //这里有一个问题需要注意，就是需要找到一个可以点击的View
                    Log.i(TAG, "Click" + ",isClick:" + info.isClickable());
//                    info.performAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
                    info.performAction(AccessibilityNodeInfo.ACTION_CLICK);

                    AccessibilityNodeInfo parent = info.getParent();
                    while (parent != null) {
                        Log.i(TAG, "parent isClick:" + parent.isClickable());
                        if (parent.isClickable()) {
                            parent.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                            break;
                        }
                        parent = parent.getParent();
                    }
                }
            }
        } else {
            for (int i = 0; i < info.getChildCount(); i++) {
                if (info.getChild(i) != null) {
                    findWidget(info.getChild(i));
                }
            }
        }
    }

    /**
     * 通知栏打开微信
     *
     * @param event 事件
     */
    private void openAppByNotification(AccessibilityEvent event) {
        Log.d(TAG, "openAppByNotification");
        if (event.getParcelableData() != null && event.getParcelableData() instanceof Notification) {
            Notification notification = (Notification) event.getParcelableData();
            try {
                PendingIntent pendingIntent = notification.contentIntent;
                pendingIntent.send();
            } catch (PendingIntent.CanceledException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 填充输入框
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private boolean fillInputBar(String reply) {
        AccessibilityNodeInfo rootNode = getRootInActiveWindow();
        if (rootNode != null) {
            return findInputBar(rootNode, reply);
        }
        return false;
    }

    /**
     * 查找EditText控件
     *
     * @param rootNode 根结点
     * @param reply    回复内容
     * @return 找到返回true, 否则返回false
     */
    private boolean findInputBar(AccessibilityNodeInfo rootNode, String reply) {
        int count = rootNode.getChildCount();
        for (int i = 0; i < count; i++) {
            AccessibilityNodeInfo node = rootNode.getChild(i);
            if ("android.widget.EditText".equals(node.getClassName())) {   // 找到输入框并输入文本
                setText(node, reply);
                return true;
            }
            if (findInputBar(node, reply)) {    // 递归查找
                return true;
            }
        }
        return false;
    }

    /**
     * 设置文本
     */
    private void setText(AccessibilityNodeInfo node, String reply) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Bundle args = new Bundle();
            args.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE,
                    reply);
            node.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, args);
        } else {
            ClipData data = ClipData.newPlainText("reply", reply);
            ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            clipboardManager.setPrimaryClip(data);
            node.performAction(AccessibilityNodeInfo.ACTION_FOCUS); // 获取焦点
            node.performAction(AccessibilityNodeInfo.ACTION_PASTE); // 执行粘贴
        }
    }

    private AccessibilityNodeInfo findAction(String widget, String text) {
        // 取得当前激活窗体的根节点
        if (getRootInActiveWindow() == null) {
            return null;
        }
        // 通过文本找到当前的节点
        List<AccessibilityNodeInfo> nodes = getRootInActiveWindow().findAccessibilityNodeInfosByText(text);
        if (nodes != null) {
            for (AccessibilityNodeInfo n : nodes) {
                if (n.getClassName().equals(widget) && n.isEnabled()) {
                    return n;
                }
            }
        }
        return null;
    }

    /**
     * 查找UI控件并点击
     *
     * @param widget 控件完整名称, 如android.widget.Button, android.widget.TextView
     * @param text   控件文本
     */
    private void findAndPerformAction(String widget, String text) {
        // 取得当前激活窗体的根节点
        if (getRootInActiveWindow() == null) {
            return;
        }
        // 通过文本找到当前的节点
        List<AccessibilityNodeInfo> nodes = getRootInActiveWindow().findAccessibilityNodeInfosByText(text);
        if (nodes != null) {
            for (AccessibilityNodeInfo node : nodes) {
                if (node.getClassName().equals(widget) && node.isEnabled()) {
                    node.performAction(AccessibilityNodeInfo.ACTION_CLICK); // 执行点击
                    break;
                }
            }
        }
    }


    @Override
    public void onInterrupt() {
        Log.d(TAG, "onInterrupt...");
    }

    @Override
    protected void onServiceConnected() {
        Log.d(TAG, "onServiceConnected");
        super.onServiceConnected();
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void checkKey() {
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        if (nodeInfo == null) {
            Log.w(TAG, "rootWindow为空");
            return;
        }

        Log.i(TAG, "child count:" + nodeInfo.getChildCount());
        List<AccessibilityNodeInfo> list = nodeInfo.findAccessibilityNodeInfosByText("按住 说话");
        if (list.isEmpty()) {
            list = nodeInfo.findAccessibilityNodeInfosByText(ENVELOPE_TEXT_KEY);
            for (AccessibilityNodeInfo n : list) {
                Log.i(TAG, "-->微信红包:" + n);
                n.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                break;
            }
        } else {
            //最新的红包领起
            for (int i = list.size() - 1; i >= 0; i--) {
                AccessibilityNodeInfo node = list.get(i);
                Log.i(TAG, "long click");
                node.performAction(AccessibilityNodeInfo.ACTION_FOCUS);
                node.performAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
                break;

//                AccessibilityNodeInfo parent = list.get(i).getParent();
//                if (parent != null) {
//                    parent.performAction(AccessibilityNodeInfo.ACTION_CLICK);
//                    break;
//                }
            }
        }
    }


    public void getInfo() {
        AccessibilityNodeInfo info = getRootInActiveWindow();
        if (info != null) {
            if (info.getChildCount() == 0) {
//                Log.i(TAG, "控件名称:" + info.getClassName());
//                Log.i(TAG, "控件中的值：" + info.getText());
//                Log.i(TAG, "控件的ID:" + info.getViewIdResourceName());
//                Log.i(TAG, "点击是否出现弹窗:" + info.canOpenPopup());
            } else {
                for (int i = 0; i < info.getChildCount(); i++) {
                    if (info.getChild(i) != null) {
                        recycle(info.getChild(i));
                    }
                }
            }
        }
    }

    public void recycle(AccessibilityNodeInfo info) {
        if (info.getChildCount() == 0) {

//            Log.i(TAG, "控件名称:" + info.getClassName());
//            Log.i(TAG, "控件中的值：" + info.getText());
//            Log.i(TAG, "控件的ID:" + info.getViewIdResourceName());
//            Log.i(TAG, "点击是否出现弹窗:" + info.canOpenPopup());
//
//            控件名称:android.widget.Button
//            控件中的值：按住 说话
//            控件的ID:null
//            点击是否出现弹窗:false

            if (info.getText() != null) {
//                if ("Yeshiva".equals(info.getText().toString())) {
                if ("切换到按住说话".equals(info.getText().toString())) {
                    //这里有一个问题需要注意，就是需要找到一个可以点击的View
                    Log.i(TAG, "Click" + ",isClick:" + info.isClickable());
//                    info.performAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
                    info.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    AccessibilityNodeInfo parent = info.getParent();
                    while (parent != null) {
                        Log.i(TAG, "parent isClick:" + parent.isClickable());
                        if (parent.isClickable()) {
                            parent.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                            break;
                        }
                        parent = parent.getParent();
                    }

                }
            }

        } else {
            for (int i = 0; i < info.getChildCount(); i++) {
                if (info.getChild(i) != null) {
                    recycle(info.getChild(i));
                }
            }
        }
    }


}
